import runtime, {
  async
} from '../../lib/runtime/runtime'
import request from '../../request/index'
import {
  getSetting,
  chooseAddress,
  openSetting,
  showModal,
  showToast
} from '../../utils/asyncWx'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    height: 0,
    cartList: [],
    allChecked: true,
    allPrice: 0,
    allNum: 0,
    address: {}, //用户地址
    payList: []
  },

  //获取收货地址
  async handleAddress() {
    try {
      //获取权限状态
      const res = await getSetting()
      const flag = res.authSetting["scope.address"]
      if (!flag) {
        //权限为false去设置权限
        await openSetting()
      }
      //获取地址
      let address = await chooseAddress()
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo
      //本地缓存
      wx.setStorageSync("address", address);
    } catch (err) {
      console.log(err);
    }
  },
  //获取数据
  getData() {
    let address = wx.getStorageSync('address')
    let cartList = wx.getStorageSync('cart') || []
    this.setData({
      address,
      cartList
    })
    this.setCart(cartList)
  },
  //商品复选框切换
  cartItemChange(e) {
    //获取点击的商品id
    const goodsId = e.currentTarget.dataset.id
    let {
      cartList
    } = this.data
    //在购物车列表例找到对应商品
    let index = cartList.findIndex(x => x.goods_id === goodsId)
    cartList[index].checked = !cartList[index].checked
    //修改选中状态，修改数据
    this.setData({
      cartList
    })
    wx.setStorageSync('cart', cartList)
    //数据更新后调用计算
    this.setCart(cartList)
  },
  //全选
  cartAllChange() {
    let {
      cartList,
      allChecked
    } = this.data
    //点击切换全选状态
    allChecked = !allChecked
    //修改购物车每一项选中状态
    cartList.forEach(x => x.checked = allChecked)
    //更改数据
    this.setData({
      allChecked,
      cartList
    })
    //数据更新后调用计算
    this.setCart(cartList)
  },
  //修改商品数量
  async changeCartNum(e) {
    const {
      state,
      id
    } = e.currentTarget.dataset
    let {
      cartList
    } = this.data
    let index = cartList.findIndex(x => x.goods_id == id)
    //数量小于1是删除商品
    if (cartList[index].num === 1 && state === -1) {
      const res = await showModal('是否移除购物车')
      //移除购物车
      if (res.confirm) {
        cartList.splice(index, 1)
      }
    } else {
      // 修改数量
      cartList[index].num += state
    }
    this.setData({
      cartList
    })
    wx.setStorageSync('cart', cartList)
    //修改数据重新计算
    this.setCart(cartList)
  },
  //价格计算
  setCart(cartList) {
    let {
      allChecked,
      allPrice,
      allNum
    } = this.data
    //初始化数据
    allChecked = true
    allPrice = 0
    allNum = 0
    //判断每一项商品的选中状态
    cartList.forEach(x => {
      if (x.checked) {
        allPrice += x.num * x.goods_price
        allNum += x.num
      } else {
        allChecked = false
      }
    })
    //没有商品取消全选
    allChecked = cartList.length != 0 ? allChecked : false
    this.setData({
      allChecked,
      allNum,
      allPrice
    })
  },
  //点击结算
  async settlement() {
    let {
      cartList,
      address,
      allNum,
      payList
    } = this.data
    //收货地址判断
    if (!address.userName) {
      await showToast('未选择收货地址')
      return
    }
    if (allNum === 0) {
      await showToast('未勾选商品')
      return
    }
    //跳转支付
    cartList.forEach(x => x.checked ? payList.push(x) : '')
    this.setData({
      payList
    })
    wx.navigateTo({
      url: '/pages/pay/index',
      success: (res) => {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          data: payList
        })
      }
    })
    this.setData({
      payList: []
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let my_height = wx.getSystemInfoSync().windowHeight
    this.setData({
      height: my_height - 45 - 85 - 48
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData()
    console.log(this.data.cartList)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})